package cn.chiship.framework.upms.biz.user.service.impl;

import cn.chiship.framework.common.util.CodeGenerationUtil;
import cn.chiship.framework.upms.biz.user.entity.UpmsOrganizationExample;
import cn.chiship.framework.upms.biz.user.entity.UpmsUserOrganization;
import cn.chiship.framework.upms.biz.user.entity.UpmsUserOrganizationExample;
import cn.chiship.framework.upms.biz.user.mapper.UpmsOrganizationMapper;
import cn.chiship.framework.upms.biz.user.mapper.UpmsUserOrganizationMapper;
import cn.chiship.framework.upms.biz.user.service.UpmsOrganizationService;
import cn.chiship.framework.upms.biz.user.service.UpmsUserOrganizationService;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.base.constants.BaseConstants;
import cn.chiship.sdk.core.enums.BaseResultEnum;
import cn.chiship.sdk.core.id.SnowflakeIdUtil;
import cn.chiship.sdk.core.util.ShareCodeUtil;
import cn.chiship.sdk.core.util.StringUtil;
import cn.chiship.sdk.framework.base.BaseServiceImpl;

import cn.chiship.framework.upms.biz.user.entity.UpmsOrganization;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 组织业务接口实现层
 * 2021/9/27
 *
 * @author lijian
 */
@Service
public class UpmsOrganizationServiceImpl extends BaseServiceImpl<UpmsOrganization, UpmsOrganizationExample> implements UpmsOrganizationService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UpmsOrganizationServiceImpl.class);

    @Resource
    UpmsOrganizationMapper upmsOrganizationMapper;
    @Resource
    UpmsUserOrganizationService upmsUserOrganizationService;


    @Override
    public BaseResult insertSelective(UpmsOrganization upmsOrganization) {
        UpmsOrganizationExample upmsOrganizationExample = new UpmsOrganizationExample();
        upmsOrganizationExample.createCriteria().andOrganizationNameEqualTo(upmsOrganization.getOrganizationName()).andTypeEqualTo(upmsOrganization.getType());
        UpmsOrganizationExample.Criteria criteria = upmsOrganizationExample.createCriteria();
        criteria.andOrganizationCodeEqualTo(upmsOrganization.getOrganizationCode()).andTypeEqualTo(upmsOrganization.getType());
        upmsOrganizationExample.or(criteria);


        List<UpmsOrganization> upmsOrganizationList = upmsOrganizationMapper.selectByExample(upmsOrganizationExample);
        if (upmsOrganizationList.isEmpty()) {
            BaseResult baseResult = super.insertSelective(upmsOrganization);
            if (baseResult.isSuccess()) {
                saveOrgUser(upmsOrganization);
            }
            return baseResult;
        } else {
            return BaseResult.error(BaseResultEnum.EXCEPTION_DATA_BASE_REPEAT, "编号或名称已存在，请重新输入");
        }
    }

    @Override
    public BaseResult updateByPrimaryKeySelective(UpmsOrganization upmsOrganization) {
        upmsOrganization.setGmtModified(System.currentTimeMillis());

        UpmsOrganizationExample upmsOrganizationExample = new UpmsOrganizationExample();
        upmsOrganizationExample.createCriteria().andOrganizationNameEqualTo(upmsOrganization.getOrganizationName()).andTypeEqualTo(upmsOrganization.getType())
                .andIdNotEqualTo(upmsOrganization.getId());
        UpmsOrganizationExample.Criteria criteria = upmsOrganizationExample.createCriteria();
        criteria.andOrganizationCodeEqualTo(upmsOrganization.getOrganizationCode()).andTypeEqualTo(upmsOrganization.getType()).andIdNotEqualTo(upmsOrganization.getId());
        upmsOrganizationExample.or(criteria);

        List<UpmsOrganization> upmsOrganizationList = upmsOrganizationMapper.selectByExample(upmsOrganizationExample);
        if (upmsOrganizationList.isEmpty()) {
            BaseResult baseResult = super.updateByPrimaryKeySelective(upmsOrganization);
            if (baseResult.isSuccess()) {
                saveOrgUser(upmsOrganization);
            }
            return baseResult;
        } else {
            return BaseResult.error(BaseResultEnum.EXCEPTION_DATA_BASE_REPEAT, "编号或名称已存在，请重新输入");
        }
    }

    @Override
    public BaseResult deleteByExample(UpmsOrganizationExample upmsOrganizationExample) {
        List<UpmsOrganization> upmsOrganizations = upmsOrganizationMapper.selectByExample(upmsOrganizationExample);
        super.deleteByExample(upmsOrganizationExample);
        List<String> orgIds = new ArrayList<>();
        for (UpmsOrganization organization : upmsOrganizations) {
            orgIds.add(organization.getId());
        }
        if (!orgIds.isEmpty()) {
            UpmsUserOrganizationExample upmsUserOrganizationExample = new UpmsUserOrganizationExample();
            upmsUserOrganizationExample.createCriteria().andOrganizationIdIn(orgIds);
            upmsUserOrganizationService.deleteByExample(upmsUserOrganizationExample);
        }
        return BaseResult.ok();
    }

    @Override
    public BaseResult generateOrgCode(String pid, Byte type) {
        UpmsOrganization upmsOrganization = upmsOrganizationMapper.selectByPrimaryKey(pid);

        String maxOrgCode = upmsOrganizationMapper.getMaxOrgCodeByPid(pid);
        long serialNumber = 1;
        String codePre = null;

        if (!StringUtil.isNullOrEmpty(maxOrgCode)) {
            String lastThree = maxOrgCode.substring(maxOrgCode.length() - 3);
            serialNumber = Long.valueOf(lastThree) + 1;
        }
        if (!StringUtil.isNull(upmsOrganization)) {
            codePre = upmsOrganization.getOrganizationCode();
        }
        return BaseResult.ok(CodeGenerationUtil.generateOrgCode(type, codePre, serialNumber));
    }

    @Override
    public BaseResult invitationCode(String id) {
        UpmsOrganization upmsOrganization = upmsOrganizationMapper.selectByPrimaryKey(id);
        if (StringUtil.isNull(upmsOrganization)) {
            return BaseResult.error("组织机构不存在，请确认参数！");
        }
        upmsOrganization.setInvitationCode(ShareCodeUtil.generateSerialCode(Long.valueOf(id)));
        super.updateByPrimaryKeySelective(upmsOrganization);
        return BaseResult.ok();
    }

    @Override
    public BaseResult getByInvitation(String code) {
        try {
            Long id = ShareCodeUtil.codeToId(code);
            UpmsOrganization upmsOrganization = upmsOrganizationMapper.selectByPrimaryKey(StringUtil.getString(id));
            return BaseResult.ok(upmsOrganization);
        } catch (Exception e) {
            return BaseResult.error("无效的邀请码！");
        }
    }

    @Override
    public BaseResult setChargePerson(String organizationId, String userId, String realName) {
        UpmsOrganization organization = upmsOrganizationMapper.selectByPrimaryKey(organizationId);
        if (StringUtil.isNull(organization)) {
            return BaseResult.error("组织机构不存在,请确认传递参数！");
        }
        organization.setChargeInfo(userId + ":" + realName);
        return super.updateByPrimaryKeySelective(organization);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult adjustment(String organizationId, String targetOrg) {
        UpmsOrganization organization = upmsOrganizationMapper.selectByPrimaryKey(organizationId);
        if (StringUtil.isNull(organization)) {
            return BaseResult.error("组织机构不存在,请确认传递参数！");
        }
        organization.setPid(targetOrg);
        BaseResult baseResult = generateOrgCode(targetOrg, organization.getType());
        if (!baseResult.isSuccess()) {
            return baseResult;
        }
        organization.setOrganizationCode(baseResult.getData().toString());
        return super.updateByPrimaryKeySelective(organization);
    }

    public void saveOrgUser(UpmsOrganization organization) {
        String chargeInfo = organization.getChargeInfo();
        if (!StringUtil.isNullOrEmpty(organization.getChargeInfo())) {
            String[] chargeInfos = chargeInfo.split(":");
            String userId = chargeInfos.length > 1 ? chargeInfos[0] : chargeInfo;
            String orgId = organization.getId();
            UpmsUserOrganization upmsUserOrganization = new UpmsUserOrganization();
            upmsUserOrganization.setOrganizationId(orgId);
            //后期FullOrganizationId的获取要修改
            upmsUserOrganization.setFullOrganizationId(orgId);
            upmsUserOrganization.setUserId(userId);
            upmsUserOrganizationService.insertSelective(upmsUserOrganization);
        }
    }
}
